package com.xiaohua.api.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xiaohua.api.domain.XhOperation;
import com.xiaohua.api.mapper.XhOperationMapper;
import com.xiaohua.api.service.IOperationLogService;
import com.xiaohua.common.core.domain.AjaxResult;
import com.xiaohua.common.utils.StringUtils;

/**
 * API操作日志服务实现类
 * 
 * @author 小花
 * @date 2023-07-15
 */
@Service
public class OperationLogServiceImpl implements IOperationLogService {
    
    private static final Logger log = LoggerFactory.getLogger(OperationLogServiceImpl.class);
    
    @Autowired
    private XhOperationMapper operationMapper;

    @Override
    public boolean logOperation(Long userId, String operationType, int status) {
        try {
            XhOperation operation = new XhOperation();
            operation.setUserId(userId);
            operation.setOperationType(operationType);
            operation.setStatus(status);
            
            return operationMapper.insertOperation(operation) > 0;
        } catch (Exception e) {
            log.error("记录操作日志失败：userId={}, operationType={}, status={}, error={}", 
                    userId, operationType, status, e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean logOperation(Long userId, Long fileId, String operationType, int status) {
        try {
            XhOperation operation = new XhOperation();
            operation.setUserId(userId);
            operation.setFileId(fileId);
            operation.setOperationType(operationType);
            operation.setStatus(status);
            
            return operationMapper.insertOperation(operation) > 0;
        } catch (Exception e) {
            log.error("记录操作日志失败：userId={}, fileId={}, operationType={}, status={}, error={}", 
                    userId, fileId, operationType, status, e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean logOperationWithMultipleFiles(Long userId, List<Long> fileIds, String operationType, int status) {
        if (fileIds == null || fileIds.isEmpty()) {
            return logOperation(userId, operationType, status);
        }
        
        try {
            List<XhOperation> operations = new ArrayList<>();
            
            for (Long fileId : fileIds) {
                XhOperation operation = new XhOperation();
                operation.setUserId(userId);
                operation.setFileId(fileId);
                operation.setOperationType(operationType);
                operation.setStatus(status);
                operations.add(operation);
            }
            
            return operationMapper.batchInsertOperation(operations) > 0;
        } catch (Exception e) {
            log.error("批量记录操作日志失败：userId={}, fileIds.size={}, operationType={}, status={}, error={}", 
                    userId, fileIds.size(), operationType, status, e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean logOperationFromResult(Long userId, Object result, String operationType, boolean isMultiFile) {
        if (result == null) {
            return logOperation(userId, operationType, 500);
        }
        
        try {
            // 处理AjaxResult类型
            if (result instanceof AjaxResult) {
                AjaxResult ajaxResult = (AjaxResult) result;
                int status = ajaxResult.isSuccess() ? 200 : 500;
                
                // 尝试提取多文件ID列表的情况
                if (isMultiFile) {
                    try {
                        // 尝试从images、fileIds、files等多种可能的字段中提取文件ID列表
                        List<Long> fileIds = extractFileIds(ajaxResult);
                        if (fileIds != null && !fileIds.isEmpty()) {
                            return logOperationWithMultipleFiles(userId, fileIds, operationType, status);
                        }
                    } catch (Exception e) {
                        log.warn("从多文件结果中提取文件ID失败：{}", e.getMessage());
                    }
                }
                
                // 尝试提取单文件ID的情况
                Long fileId = extractFileId(ajaxResult);
                if (fileId != null) {
                    return logOperation(userId, fileId, operationType, status);
                }
                
                // 只记录基本操作信息
                return logOperation(userId, operationType, status);
            }
            
            // 其他类型的结果，只记录基本操作信息
            return logOperation(userId, operationType, 200);
        } catch (Exception e) {
            log.error("从结果中提取操作日志信息失败: userId={}, operationType={}, error={}", 
                    userId, operationType, e.getMessage(), e);
            return logOperation(userId, operationType, 500);
        }
    }
    
    /**
     * 从AjaxResult中提取单个文件ID
     */
    private Long extractFileId(AjaxResult result) {
        try {
            // 尝试从多个可能的字段名中提取
            String[] possibleFields = {"fileId", "id", "documentId"};
            
            for (String field : possibleFields) {
                Object value = result.get(field);
                if (value != null) {
                    if (value instanceof Number) {
                        return ((Number) value).longValue();
                    } else if (value instanceof String) {
                        try {
                            return Long.parseLong((String) value);
                        } catch (NumberFormatException e) {
                            // 忽略格式错误
                        }
                    }
                }
            }
            
            // 如果有data字段，且data是Map类型，尝试从data中提取
            Object dataObj = result.get("data");
            if (dataObj instanceof Map) {
                Map<String, Object> dataMap = (Map<String, Object>) dataObj;
                for (String field : possibleFields) {
                    Object value = dataMap.get(field);
                    if (value != null) {
                        if (value instanceof Number) {
                            return ((Number) value).longValue();
                        } else if (value instanceof String) {
                            try {
                                return Long.parseLong((String) value);
                            } catch (NumberFormatException e) {
                                // 忽略格式错误
                            }
                        }
                    }
                }
            }
            
            return null;
        } catch (Exception e) {
            log.warn("提取文件ID时发生错误：{}", e.getMessage());
            return null;
        }
    }
    
    /**
     * 从AjaxResult中提取多个文件ID
     */
    @SuppressWarnings("unchecked")
    private List<Long> extractFileIds(AjaxResult result) {
        List<Long> fileIds = new ArrayList<>();
        
        try {
            // 尝试从常用字段中提取文件ID列表
            String[] possibleListFields = {"fileIds", "images", "files", "documentIds", "imageUrls"};
            
            for (String field : possibleListFields) {
                Object value = result.get(field);
                if (value instanceof List) {
                    List<?> list = (List<?>) value;
                    for (Object item : list) {
                        if (item instanceof Number) {
                            fileIds.add(((Number) item).longValue());
                        } else if (item instanceof String && StringUtils.isNumeric((String) item)) {
                            fileIds.add(Long.parseLong((String) item));
                        } else if (item instanceof Map) {
                            // 如果列表项是对象，尝试提取id字段
                            Object id = ((Map<String, Object>) item).get("id");
                            if (id instanceof Number) {
                                fileIds.add(((Number) id).longValue());
                            } else if (id instanceof String && StringUtils.isNumeric((String) id)) {
                                fileIds.add(Long.parseLong((String) id));
                            }
                        }
                    }
                    if (!fileIds.isEmpty()) {
                        return fileIds;
                    }
                }
            }
            
            // 检查data字段
            Object dataObj = result.get("data");
            if (dataObj instanceof Map) {
                Map<String, Object> dataMap = (Map<String, Object>) dataObj;
                for (String field : possibleListFields) {
                    Object value = dataMap.get(field);
                    if (value instanceof List) {
                        List<?> list = (List<?>) value;
                        for (Object item : list) {
                            if (item instanceof Number) {
                                fileIds.add(((Number) item).longValue());
                            } else if (item instanceof String && StringUtils.isNumeric((String) item)) {
                                fileIds.add(Long.parseLong((String) item));
                            } else if (item instanceof Map) {
                                // 如果列表项是对象，尝试提取id字段
                                Object id = ((Map<String, Object>) item).get("id");
                                if (id instanceof Number) {
                                    fileIds.add(((Number) id).longValue());
                                } else if (id instanceof String && StringUtils.isNumeric((String) id)) {
                                    fileIds.add(Long.parseLong((String) id));
                                }
                            }
                        }
                        if (!fileIds.isEmpty()) {
                            return fileIds;
                        }
                    }
                }
            }
            
            return fileIds;
        } catch (Exception e) {
            log.warn("提取多文件ID列表时发生错误：{}", e.getMessage());
            return fileIds;
        }
    }
} 